from amscms import settings
from amscms.core.utils.email import send_email
from amscms.recaptcha_works.fields import RecaptchaField
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.utils.http import int_to_base36
from django.utils.translation import ugettext as _


class UserSignupForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and password.
    """
    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'[\w.@+-]+$',
        help_text=_("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
        error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
    password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
        help_text=_("Enter the same password as above, for verification."))
    first_name = forms.CharField(label=_("First name"), max_length=30)
    last_name = forms.CharField(label=_("Last name"), max_length=30)
    email = forms.EmailField(label=_("E-mail"), max_length=75)
    recaptcha = RecaptchaField(label=_("Captcha"), required=True)
    
    class Meta:
        model = User
        fields = ("username", "first_name", "last_name", "email",)

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(_("The two password fields didn't match."))
        return password2
    
    def save(self, commit=True, domain_override=None, use_https=False,
             email_template_name="registration/signup_email.html",
             token_generator=default_token_generator):
        user = super(UserSignupForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            # User is not active after sign-up
            user.is_active = False
            user.save()
            """
            Generates a one-use only link for activating account and sends to the user
            """
            if not domain_override:
                current_site = Site.objects.get_current()
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override
            c = {
                'subject': _(u"Account activation link for %(site_name)s") % {'site_name': site_name, },
                'site_name': site_name,
                'domain': domain,
                'protocol': use_https and 'https' or 'http',
                'uid': int_to_base36(user.id),
                'user': user,
                'token': token_generator.make_token(user),
            }
            send_email(user.email, c, settings.DEFAULT_FROM_EMAIL,
                       "registration/signup_email.txt",
                       "registration/signup_email.html")    
                
        return user
    
